package com.tyqx.apiutil.common;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;

public class CnyExchangeUsdRateUtil {

    public static BigDecimal getCnyExchangeUsdRate(){
        try {
            // Setting URL
            String url_str = "https://v6.exchangerate-api.com/v6/ba260591e03497158b067692/latest/USD";

// Making Request
            URL url = new URL(url_str);
            HttpURLConnection request = (HttpURLConnection) url.openConnection();
            request.connect();

// Convert to JSON
            JsonParser jp = new JsonParser();
            JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
            JsonObject jsonobj = root.getAsJsonObject();

// Accessing object
            JsonObject conversion_rates = jsonobj.getAsJsonObject("conversion_rates");
            BigDecimal cnyRate = conversion_rates.get("CNY").getAsBigDecimal();
            return cnyRate;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
